package cn.edu.zafu.bigdata.x.zyy;

//服务端代码（Server.java）
import java.io.*;
import java.net.*;

class Server {
    public static void main(String[] args) {
        try {
            // 创建服务器端的ServerSocket，监听端口号1234
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("Server is running and waiting for client connection...");

            // 服务器无限循环，等待客户端连接
            while (true) {
                // 等待接受客户端的连接，此方法会阻塞，直到一个连接建立
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                // 获取输入流，读取客户端发送的消息
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // 获取输出流，向客户端发送消息
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                // 读取客户端发送的消息
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Client says: " + inputLine);

                    // 将消息回复给客户端
                    out.println("Server received: " + inputLine);
                }
                // 关闭连接
                in.close();
                out.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//客户端代码（Client.java）

public class Client {
    public static void main(String[] args) {
        try {
            // 创建客户端的Socket，连接到服务器的IP和端口号
            Socket socket = new Socket("服务器的IP地址", 1234);
            System.out.println("Connected to server.");

            // 获取输出流，向服务器发送消息
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            // 获取输入流，读取服务器的回复
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 读取用户输入，并发送给服务器
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);

                // 从服务器读取回复
                String fromServer = in.readLine();
                System.out.println("Server says: " + fromServer);

                // 如果用户输入“bye”，则退出循环
                if (userInput.equals("bye")) {
                    break;
                }
            }

            // 关闭连接
            in.close();
            out.close();
            stdIn.close();
            socket.close();
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to host.");
            e.printStackTrace();
        }
    }
}